package game;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import utils.JDBCUtil;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.sql.PreparedStatement;
import java.util.Map;
import java.util.Objects;

public class Login{

    public static class LoginWindow extends JFrame implements ActionListener {
        private final Image img = ImageManager.loadImage("src/images/bg/丛雨.png");
        int frameWidth = 600; // 设置宽度
        int frameHeight = 400; // 设置高度
        JLabel userlabel;
        JTextField usernameField;
        JLabel passwordlabel;
        JPasswordField passwordField;
        JButton loginButton;
        public LoginWindow() {
            setBounds(LoginFrame.getScreenWidth() / 2 - 300, LoginFrame.getScreenHeight() / 2 - 200, frameWidth, frameHeight);
            setResizable(false);
            //窗口不可调节
            setIconImage(img);
            setTitle("登录界面");
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            JPanel backgroundPanel = new JPanel() {
                protected void paintComponent(Graphics g) {
                    super.paintComponent(g);
                    // 创建一个带有透明度的 BufferedImage
                    BufferedImage bufferedImage = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB);
                    Graphics2D g2d = bufferedImage.createGraphics();
                    // 设置透明度为 0.5，并将图像变暗
                    g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.4f));
                    // 绘制黑色矩形以覆盖整个图像，使其变暗
                    g2d.setColor(new Color(0, 0, 0, 200));
                    g2d.fillRect(0, 0, getWidth(), getHeight());
                    g2d.drawImage(img, 0, 0, getWidth(), getHeight(), this);
                    g2d.dispose();
                    // 绘制带有透明度的 BufferedImage
                    g.drawImage(bufferedImage, 0, 0, null);
                }
            };

            getContentPane().add(backgroundPanel);

            Box vbox = Box.createVerticalBox();

            Box ubox = Box.createHorizontalBox();
            userlabel = new JLabel("用户名：");
            usernameField = new JTextField(20);
            ubox.add(userlabel);
            ubox.add(Box.createHorizontalStrut(10));
            ubox.add(usernameField);

            Box pbox = Box.createHorizontalBox();
            passwordlabel = new JLabel("密    码：");
            passwordField = new JPasswordField(15);
            pbox.add(passwordlabel);
            pbox.add(Box.createHorizontalStrut(10));
            pbox.add(passwordField);

            Box btnbox = Box.createHorizontalBox();
            btnbox.add(Box.createHorizontalStrut(40));
            loginButton = new JButton("登录");
            btnbox.add(loginButton);

            vbox.add(Box.createVerticalStrut(110));
            vbox.add(ubox);
            vbox.add(Box.createVerticalStrut(20));
            vbox.add(pbox);
            vbox.add(Box.createVerticalStrut(60));
            vbox.add(btnbox);

            backgroundPanel.add(vbox);

            setVisible(true);
            loginButton.addActionListener(this);
            //传入的参数默认指向当前类的actionPerformed


        }
        JdbcTemplate jdbcTemplate = new JdbcTemplate(JDBCUtil.getDataSource());
        @Override

        public void actionPerformed(ActionEvent e) {//按钮点击事件
            if (e.getSource() == loginButton) {//事件源是否是登录按钮

                String username = usernameField.getText();//获取用户输入的用户名
                String password = new String(passwordField.getPassword());
                int score;
                //密码以字符数组形式存储 故需要转化成字符串形式
                if(username.isEmpty()){
                    return;
                }//为空不触发
                // 在这里可以添加验证逻辑，例如检查用户名和密码是否匹配数据库中的记录
                try {
                    String sql = "select id,password,MaxScore from user where username = ?";
                    Map<String, Object> map = jdbcTemplate.queryForMap(sql,username);
                    if (!map.isEmpty()) {//找到用户返回密码
                        String password1 = (String) map.get("password");
                        //获取密码
                        score = (int) map.get("MaxScore");
                        if (password.equals(password1)) {
                            JOptionPane.showMessageDialog(this, "登录成功");
                            int id = (int) map.get("id");
                            GameData.highest_score = score;
                            GameData.id = id;
                            dispose();
                        } else {
                            JOptionPane.showMessageDialog(this, "密码错误");
                        }
                    }
                }catch (Exception exception) {
                    int result = JOptionPane.showConfirmDialog(this,"无此用户，要用当前的信息，创建新的用户吗？",null,JOptionPane.YES_NO_OPTION);
                    if (result == JOptionPane.YES_OPTION){
                        String sql1 = "insert into user (username,password,MaxScore) values (?,?,?)";
                        String sql2 = "insert into score (id,Score,All_jump,jump_catus,avoid_pterosaur) values (?,?,?,?,?)";
                        KeyHolder keyHolder = new GeneratedKeyHolder();
                        jdbcTemplate.update(connection -> {
                            PreparedStatement ps = connection.prepareStatement(sql1, new String[]{"id"});
                            ps.setString(1, username);
                            ps.setString(2, password);
                            ps.setInt(3,GameData.highest_score);
                            return ps;
                        }, keyHolder);
                        GameData.id= Objects.requireNonNull(keyHolder.getKey()).intValue();
                        //在主键不为0时拆包，将id赋值
                        String unlock = "alter table score drop foreign key score_user_id";
                        jdbcTemplate.update(unlock);
                        int j = jdbcTemplate.update(sql2,GameData.id,GameData.current_score,GameData.All_jump
                                ,GameData.jump_catus,GameData.avoid_pterosaur);
                        String lock = "alter table score add constraint score_user_id foreign key (id) references user(id)";
                        jdbcTemplate.update(lock);
                        // alter table user auto_increment = 1;
                        if (j > 0){
                            JOptionPane.showMessageDialog(this, "创建成功");
                        }else {
                            JOptionPane.showMessageDialog(this, "创建失败");
                        }
                        dispose();
                    }else {
                        dispose();
                    }
                }
                //如果用户名和密码匹配，则显示登录成功，否则显示账户名或密码错误
            }
        }

    }


}

